<?php
//检查今天生效的延时订单、品牌账户是否过期（每天凌晨0点）
ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\model\brand\Brand as mBrand;
use Biz\model\brand\BrandOrder;
use Biz\model\brandAccount\BrandAccountAuth;
use Biz\model\brandAccount\BrandAccountInfo;
use Biz\service\brand\BrandExpireService;
use Biz\service\brand\Order;
use Biz\service\brandPack\RenewPackageService;
use Doraemon\cache\User as CacheUser;
use Doraemon\service\DingTalkAlert;

//今天生效的延时订单
$orderUids = [];
$orderList = BrandOrder::getTodayInOrder();
foreach ($orderList as $orderInfo) {
    $orderUids[] = $orderInfo['uid'];
    var_dump('今天入驻的品牌#brand_id:' . $orderInfo['brand_id'] . '#brand_name:' . $orderInfo['brand_name'] . '#dsn:' . $orderInfo['dsn']);
    checkAuth($orderInfo['brand_id']);
    Order::afterStartBrandAccount($orderInfo, true);
    BrandExpireService::trigger($orderInfo['brand_id']);
    RenewPackageService::effectBrandRenewPackage($orderInfo['brand_id']);
}

//入驻过期的品牌
$today = date('Y-m-d');
$where = [
    'type' => BrandAccountInfo::ACCOUNT_TYPE_BRAND,
    'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED,
    'in_end_time[<]' => $today,
];
$accountList = BrandAccountInfo::getAllByWhere($where);

foreach ($accountList as $account) {
    if (empty($orderUids) || !in_array($account['uid'], $orderUids)) {//入驻时间过期
        expireBrand($account['id'], $account['brand_id'], $account['uid']);
        print_r('入驻过期的品牌');
        print_r([
            'account_id' => $account['id'],
            'uid' => $account['uid'],
            'brand_id' => $account['brand_id'],
            'brand_type' => $account['brand_type'],
            'account_status' => $account['account_status'],
            'in_start_time' => $account['in_start_time'],
            'in_end_time' => $account['in_end_time'],
        ]);
        print_r("\n");
    }
}

function expireBrand($accountId, $brandId, $uid)
{
    BrandAccountInfo::updateData([
        'brand_type' => mBrand::BRAND_TYPE_EXPIRE,
        'account_status' => BrandAccountInfo::ACCOUNT_STATUS_EXPIRE,
        'auth_status' => BrandAccountInfo::AUTH_STATUS_EXPIRE
    ], [
        'id' => $accountId
    ]);
    BrandAccountAuth::updateData([
        'auth_status' => BrandAccountAuth::AUTH_STATUS_EXPIRE,
    ], [
        'account_id' => $accountId,
        'auth_status' => BrandAccountAuth::AUTH_STATUS_USED
    ]);
    //过期：1，权益为：0
    mBrand::updateBrandInfoById($brandId, ['status' => mBrand::STATUS_DELETE, 'pack_type' => 0, 'brand_type' => mBrand::BRAND_TYPE_EXPIRE, 'package_id' => 0]);

    \Biz\service\brand\BrandExpireService::trigger($brandId);

    if ($uid) {
        $userInfo = \Doraemon\model\Member::getOne($uid);
        if ($userInfo && $userInfo['type'] == \Doraemon\model\Member::AUTH_USER_BRAND) {
            //删除品牌身份
            \Doraemon\model\Member::updateUserInfo($uid, [
                'type' => \Doraemon\model\Member::USER_COMMON,
            ]);

            //强制退出登录
            \Doraemon\cache\UserAuthStatus::setAuthType($uid, \Doraemon\model\Member::USER_COMMON);

            \Doraemon\cache\EsUpdateCollector::insert($uid);
            // 换绑用户或者身份变更，投队列
            \Doraemon\cache\EsUpdateCollector::multiInsertBrandIdsForWikiBasic([$brandId]);
            // 删除用户缓存信息
            CacheUser::deleteUserInfo($uid);
        }
    }
}


function checkAuth($brandId)
{
    $brandInfo = mBrand::getInfo($brandId);
    $accountInfo = BrandAccountInfo::getOneByWhere([
        'brand_id' => $brandId,
        'type' => BrandAccountInfo::ACCOUNT_TYPE_BRAND,
        'account_status[!]' => BrandAccountInfo::ACCOUNT_STATUS_DEL
    ]);
    $authInfo = BrandAccountAuth::getOneByWhere(['account_id' => $accountInfo['id'], 'ORDER' => ['id' => 'DESC']]);
    if ($authInfo['auth_status'] != BrandAccountAuth::AUTH_STATUS_PASS || !$authInfo) {
        $title = '品牌异常通知';
        $brandName = $brandInfo['brand_name'];
        $uid = $accountInfo['uid'];
        $phone = $authInfo ? $authInfo['phone'] : '';
        $msg = <<<MSG
## {$title}
- 品牌id: **{$brandId}**
- 品牌名称: **{$brandName}**
- 关联账户uid: **{$uid}** 
- 手机号: **{$phone}**
### 该品牌套餐已生效，但没有检测到被审核通过的认证信息，请运营同学及时确认。
MSG;
        DingTalkAlert::sendMarkdownMsg(DingTalkAlert::BRAND_ABNORMAL_KEY, $title, $msg, true);
    }
}